package org.springblade.pm.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.tool.api.R;
import org.springblade.pm.entity.Plan;
import org.springblade.pm.entity.PlanDetails;
import org.springblade.pm.entity.PlanMilestone;
import org.springblade.pm.service.IPlanService;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("planapi")
@AllArgsConstructor
public class PlanController {
	private IPlanService planService;


	/**
	 * 获得版本号列表
	 * @param
	 * @return
	 */
	@GetMapping("/getVersionList")
	@ApiOperation(value = "获得版本号列表")
	public R<List<Object>> getVersionList(Integer projectId){
		QueryWrapper<Plan> wrapper = new QueryWrapper<>();
		wrapper.eq("pid",projectId).select("version").orderByDesc("version");
		List<Object> list = planService.listObjs(wrapper);
		for (int i = 0; i <list.size(); i++) {
			list.set(i,list.get(i).toString());
		}
		return R.data(list);
	}

	/**
	 * 获得计划
	 * @param projectId
	 * @return
	 */
	@GetMapping("/selectPlan")
	@ApiOperation(value = "获得计划")
	public R<Plan> selectPlan(Integer projectId,String version){
		if(version==null||"".equals(version)){
			List<Object> list = getVersionList(projectId).getData();
			if(list.size()<1){
				return R.data(null);
			}else {
				return R.data(planService.selectPlan(projectId, list.get(0).toString()));
			}
		}else {
			return R.data(planService.selectPlan(projectId, version));
		}
	}

	/**
	 * 新增或修改计划
	 * @param map
	 * @param bladeUser
	 * @return
	 */
	@PostMapping("/submitPlan")
	@ApiOperation(value = "新增或修改计划")
	public R submitPlan(@RequestBody Map<String,Object> map, BladeUser bladeUser) {
		try {
			Plan plan = new Plan();
			Integer projectId = Integer.valueOf(map.get("pid").toString());
			plan.setPid(projectId);
			plan.setCreateBy(bladeUser.getUserId());
			plan.setCreatetime(new Date(System.currentTimeMillis()));
			plan.setStatus(Integer.valueOf(map.get("status").toString()));
			if(map.get("version")!=null){
				plan.setVersion(Float.valueOf(map.get("version").toString()));
			}else{
				//设置最新版本号
				List<Object> list = getVersionList(projectId).getData();
				if (list.size() < 1) {
					plan.setVersion(1.0f);
				} else {
					Float version = Float.valueOf(list.get(0).toString());
					plan.setVersion(1.0f + version);
				}
			}

			planService.save(plan);

			List<Map<String, Object>> pdList = (List<Map<String, Object>>) map.get("pdList");
			if (pdList.size() > 0) {
				for (Map<String, Object> pdmap : pdList) {
					PlanDetails planDetails = new PlanDetails();
					//有问题**
					Integer planid = selectPlan(plan.getPid(), plan.getVersion().toString()).getData().getId();
					planDetails.setPid(planid);

					planDetails.setName(pdmap.get("name").toString());
					SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
					planDetails.setPlanstarttime(df.parse(pdmap.get("planstarttime").toString()));
					planDetails.setPlanendtime(df.parse(pdmap.get("planendtime").toString()));
					planDetails.setCycle(Integer.valueOf(pdmap.get("cycle").toString()));
					planDetails.setSort(Integer.valueOf(pdmap.get("sort").toString()));
					planDetails.setCreatetime(new Date(System.currentTimeMillis()));
					planDetails.setCreateBy(bladeUser.getUserId());
					Object remark = pdmap.get("remark");
					if(remark!=null){
						planDetails.setRemark(remark.toString());
					}
					planDetails.setStatus(1);
					planService.savePlanDetails(planDetails);

					List<Map<String, Object>> pmList = (List<Map<String, Object>>) pdmap.get("children");
					if (pmList.size() > 0) {
						for (Map<String, Object> pmmap : pmList) {
							PlanMilestone planMilestone = new PlanMilestone();
							//有问题**
							Integer pdId = planService.selectPlanDetails(planDetails.getPid(), planDetails.getSort()).getId();
							planMilestone.setPid(pdId);
							planMilestone.setName(pmmap.get("name").toString());
							SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
							planMilestone.setPlanstarttime(sdf.parse(pmmap.get("planstarttime").toString()));
							planMilestone.setPlanendtime(sdf.parse(pmmap.get("planendtime").toString()));
							planMilestone.setCycle(Integer.valueOf(pmmap.get("cycle").toString()) );
							planMilestone.setSort(Float.valueOf(pmmap.get("sort").toString()));
							planMilestone.setCreatetime(new Date(System.currentTimeMillis()));
							planMilestone.setCreateBy(bladeUser.getUserId());
							Object remark1 = pmmap.get("remark");
							if(remark1!=null){
								planMilestone.setRemark(remark1.toString());
							}
							planMilestone.setStatus(1);
							planService.savePlanMilestone(planMilestone);
						}
					}
				}
			}
			return R.status(true);
		} catch (Exception e) {
			e.printStackTrace();
			return R.status(false);
		}

	}

	/**
	 * 更新计划
	 * @param map
	 * @param bladeUser
	 * @return
	 */
	@PostMapping("/updatePlan")
	@ApiOperation(value = "根据id获取计划详情或者里程碑数据")
	public R updatePlan(@RequestBody Map<String,Object> map, BladeUser bladeUser){
		planService.deletePlan(Integer.valueOf(map.get("id").toString()));
		return submitPlan(map,bladeUser);
	}

	/**
	 * 根据id获取计划详情或者里程碑数据
	 * @param id
	 * @param sort
	 * @return
	 */
	@PostMapping("/getplanDetail")
	@ApiOperation(value = "根据id获取计划详情或者里程碑数据")
	public R getplanDetail(Integer id,String sort){
		return planService.getplanDetail(id,sort);
	}

	/**
	 * 获取甘特图所需要的时间数据
	 * @param projectId
	 * @param version
	 * @return
	 */
	@GetMapping("/timeList")
	@ApiOperation(value = "根据id获取计划详情或者里程碑数据")
	public R timeList(Integer projectId,String version) {
		try {
			if(version==null||"".equals(version)){
				List<Object> list = getVersionList(projectId).getData();
				if(list.size()<1){
					return R.data(0);
				}else {
					return getTimeList(projectId, list.get(0).toString());
				}
			}else {
				return getTimeList(projectId, version);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return R.data(500);
		}
	}

	private R getTimeList(Integer projectId, String version) throws ParseException {
		R<Plan> plan = selectPlan(projectId, version);

		List<Map<String, Object>> planList = new ArrayList<>();
		List<PlanDetails> pdList = plan.getData().getPdList();
		List<Date> list = new ArrayList<>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
 		for (PlanDetails pd: pdList){
			Map<String, Object> pdmap = new HashMap<>();
			pdmap.put("id",pd.getSort());
			pdmap.put("pid",pd.getSort()-1);
			pdmap.put("name",pd.getName());
			pdmap.put("startDate",sdf.format(pd.getPlanstarttime()));
			pdmap.put("endDate",sdf.format(pd.getPlanendtime()));
			if (pd.getStarttime()!=null&&!"".equals(pd.getStarttime())){
				pdmap.put("realStartDate",sdf.format(pd.getStarttime()));
			}else{
				pdmap.put("realStartDate","");
			}
			if (pd.getEndtime()!=null&&!"".equals(pd.getEndtime())){
				pdmap.put("realEndDate",sdf.format(pd.getEndtime()));
			}else {
				pdmap.put("realEndDate","");
			}

            list.add(pd.getStarttime());
            list.add(pd.getEndtime());
            list.add(pd.getPlanstarttime());
            list.add(pd.getPlanendtime());
			List<Map<String, Object>> pmmaps = new ArrayList<>();
			for (PlanMilestone pm : pd.getChildren()){
				Map<String, Object> pmmap = new HashMap<>();
				pmmap.put("id",pm.getSort());
				pmmap.put("pid",pd.getSort());
				pmmap.put("name",pm.getName());
				pmmap.put("startDate",sdf.format(pm.getPlanstarttime()));
				pmmap.put("endDate",sdf.format(pm.getPlanendtime()));
				if (pm.getStarttime()!=null&&!"".equals(pm.getStarttime())){
					pmmap.put("realStartDate",sdf.format(pm.getStarttime()));
				}else{
					pmmap.put("realStartDate","");
				}
				if (pm.getEndtime()!=null&&!"".equals(pm.getEndtime())){
					pmmap.put("realEndDate",sdf.format(pm.getEndtime()));
				}else {
					pmmap.put("realEndDate","");
				}
                list.add(pm.getStarttime());
                list.add(pm.getEndtime());
                list.add(pm.getPlanstarttime());
                list.add(pm.getPlanendtime());
               	pmmaps.add(pmmap);
            }
            pdmap.put("children",pmmaps);
            planList.add(pdmap);
        }
        //List中剔除空元素
		list.removeAll(Collections.singleton(null));
		Date stsrttime = Collections.min(list);
		Date endTime = Collections.max(list);
		String stime = sdf.format(stsrttime);
		String etime = sdf.format(endTime);

        Map<String, Object> timeMap = new HashMap();
        timeMap.put("planData",planList);
		timeMap.put("startDate",stime);
		timeMap.put("endDate",etime);
		return R.data(timeMap);
	}

}
